// SPDX-FileCopyrightText: Copyright 2025-2025 深圳市同心圆网络有限公司
// SPDX-License-Identifier: GPL-3.0-only

package group_cmd

import (
	"fmt"
	"strings"

	"gitcode.com/openseaotter/so_proto_gen_go.git/image_group_api"
	"gitcode.com/openseaotter/so_server/config"
	"gitcode.com/openseaotter/so_server/utils"
	"github.com/spf13/cobra"
)

var listGroupCmd_Offset uint32
var listGroupCmd_Limit uint32

var listGroupCmd = &cobra.Command{
	Use: "listGroup",
	RunE: func(cmd *cobra.Command, args []string) error {
		cfg, err := config.ReadServerConfig()
		if err != nil {
			return err
		}
		if cfg.SuperToken == "" {
			return fmt.Errorf("miss super token in config")
		}
		conn, err := utils.ConnGrpcServer(fmt.Sprintf("127.0.0.1:%d", cfg.ServicePort))
		if err != nil {
			return err
		}
		defer conn.Close()

		client := image_group_api.NewImageGroupApiClient(conn)

		res, err := client.List(cmd.Context(), &image_group_api.ListRequest{
			AccessToken: cfg.SuperToken,
			Offset:      listGroupCmd_Offset,
			Limit:       listGroupCmd_Limit,
		})
		if err != nil {
			return err
		}
		if res.Code != image_group_api.ListResponse_CODE_OK {
			return fmt.Errorf("%s", res.ErrMsg)
		}
		fmt.Printf("total group count %d,current offset %d\n", res.TotalCount, listGroupCmd_Offset)
		for _, group := range res.GroupList {
			fmt.Println(group.GroupName)
			fmt.Println("allow pull secret name:", strings.Join(group.PermInfo.PullSecretNameList, " "))
			fmt.Println("allow push secret name:", strings.Join(group.PermInfo.PushSecretNameList, " "))
			fmt.Println("===================================================")
		}
		return nil
	},
}

func init() {
	listGroupCmd.Flags().Uint32Var(&listGroupCmd_Offset, "offset", 0, "list image group offset")
	listGroupCmd.Flags().Uint32Var(&listGroupCmd_Limit, "limit", 10, "list image group limit")
}
